import { Component, TemplateRef, ElementRef, HostListener, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { FetchService } from "../../../core/net/fetch.service";
import { NzInputDirective, NzMessageService } from "ng-zorro-antd";
import { differenceInCalendarDays } from 'date-fns';
import * as _ from 'lodash';
import { UtilService } from "../../../core/util/util.service";
import * as moment from 'moment';
import { ActivatedRoute, Router } from '@angular/router';
import { DebugAppearance } from 'cesium';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { DispatchPlanService } from '../dispatch-plan.service';

import {NzModalRef, NzModalService} from "ng-zorro-antd/modal";
import * as Le5leTopology from "topology-bundle";
declare var Le5leTopology: any ;

const initialTotal = {
    id: "total",
    project: '水量合计',
    val1: null,
    val2: null,
    val3: null,
    val6: null,
    val7: null,
    val8: null,
    val9: null,
    val10: null,
    val11: null,
    val12: null
};
const intlTableData = [
    {
        id: "",
        project: "流量",
        val1: null,
        val2: null,
        val3: null,
        val6: null,
        val7: null,
        val8: null,
        val9: null,
        val10: null,
        val11: null,
        val12: null
    }
];
const XunHash = {
    'F': '上',
    'S': '中',
    'T': '下'
};
const tenDaysValArr = ['val1', 'val2', 'val3', 'val6', 'val7', 'val8', 'val9', 'val10', 'val11', 'val12'];

@Component({
    selector: 'app-hwh-dispatch-plan-add',
    templateUrl: './hwh-dispatch-plan-add.component.html',
    styleUrls: ['./hwh-dispatch-plan-add.component.scss']
})
export class HwhDispatchPlanAddComponent implements OnInit, OnDestroy {
    // 概划图相关 start
    canvas: Le5leTopology.Topology;
    canvasOptions: Le5leTopology.Options = {};
    rect: Le5leTopology.Rect;
    ghtData;
    infoShow = false;
    hoverItem = {
        top: '0px',
        left: '0px',
        alertLevel: '-',
        waterLevel: '-',
        limitTraffic: '-',
        flow: '-'
    };
    pensDate = {
        pens: []
    };
    // 概划图相关 end
    selectedIndex = 0;  // delete  0-年 1-月 2-旬
    yearTableTitle: string;
    monthTableTitle: string;
    tendaysTableTitle: string;
    tenDaysValArr = tenDaysValArr;
    editableTableData = [];
    valArr = ['val1', 'val2', 'val3', 'val6', 'val7', 'val8', 'val9', 'val10', 'val11', 'val12'];

    tableData = [];

    year: any;
    month: any;
    pageType: string;
    planName: string;

    tenDaysMonth: number;  // 旬计划 年月
    dataType: string;  //   上 F  中 S  下 T
    editId: string | null;
    editCache: { [key: string]: { edit: boolean; data: any } } = {};

    // 文件预览
    file = null;
    tplModal: NzModalRef;
    fileSrc = '';
    fileType = '';
    fileId = '';
    fileTypeList = ['pdf', 'png', 'jpg'];
    @ViewChild(NzInputDirective, { read: ElementRef }) inputElement: ElementRef;

    @HostListener('window:click', ['$event'])
    handleClick(e: MouseEvent): void {
        if (this.inputElement && e.target['tagName'] !== 'INPUT') {
            Object.keys(this.editCache).forEach(key => {
                this.editCache[key].edit = null;
            });
            this.calcTableData(this.editableTableData);
        }
    }

    constructor(
        private fetchService: FetchService,
        private util: UtilService,
        private message: NzMessageService,
        private routerInfo: ActivatedRoute,
        private router: Router,
        private notification: NzNotificationService,
        private dispatchService: DispatchPlanService,
        private el: ElementRef,
        private modal: NzModalService,
    ) {
    }

    ngOnInit() {
        this.initDataParams();
        this.getEditableTableData();
        window.addEventListener('resize', this.debounce(() => {
            this.onResize();
        }, 500));
    }
    ngOnDestroy(): void {
        // this.canvas && this.canvas.destroy();
    }

    // 防抖函数
    debounce(func, wait?, immediate?): any {
        let timeout;
        return () => {
            const context = this;
            const args = arguments;
            const later = () => {
                timeout = null;
                if (!immediate) {
                    func.apply(context, args);
                }
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) {
                func.apply(context, args);
            }
        };
    }

    initDataParams() {
        const xunRules = ['4', '5', '6'];
        const monthRules = ['7', '8', '9'];
        const dgRules = ['d'];
        this.pageType = this.routerInfo.snapshot.queryParams['type'];
        // 新增状态 查询 当前时间的下一个时间段的计划
        if (this.pageType === 'add') {
            const nextDate = this.dispatchService.getNextDateInterval();
            this.year = nextDate.y;
            this.month = nextDate.m;
            if (xunRules.includes(this.month)) {
                this.dataType = nextDate.dataType;
                this.planName = `${this.year}年${this.month}月${XunHash[this.dataType]}旬黄河水量调度计划指标`;
            } else if (monthRules.includes(this.month)) {
                this.planName = `${this.year}年${this.month}月份黄河水量调度计划`;
            } else if (dgRules.includes(this.month)) {
                this.planName = `${this.year}年冬灌黄河水量调度计划`;
            } else {
                this.planName = '';
                this.notification.warning(
                    '提示',
                    '该时段不能创建 黄河干流水量调度方案'
                );
            }
        } else {
            this.year = this.routerInfo.snapshot.queryParams['y'];
            this.month = this.routerInfo.snapshot.queryParams['m'];
            this.dataType = this.routerInfo.snapshot.queryParams['dataType'];
            this.planName = this.routerInfo.snapshot.queryParams['name'];
        }
        this.getFile(this.planName);
    }

    getEditableTableData(): void {
        this.editableTableData = _.cloneDeep(intlTableData);
        const initialTotalObj = _.cloneDeep(initialTotal);
        this.updateEditCache();
        const params = {
            reportId: '2',
            y: this.year,
            m: this.month,
            dataType: this.dataType,
        };
        this.fetchService.post<any>('plan/wrsReportData/query', params).subscribe(res => {
            if (Array.isArray(res) && res.length) {
                if (this.pageType === 'add') {
                    this.message.warning(`${this.planName} 已创建,请编辑`);
                }
                this.editableTableData = _.concat(res, [initialTotalObj]);
                this.editableTableData[0].project = "平均日流量";
                this.calcTableData(this.editableTableData);
            } else {
                this.editableTableData = _.concat(this.editableTableData, [initialTotalObj]);
            }
            this.editableTableData[0].project = "平均日流量";
            this.updateEditCache();
            this.getMapData();
        });
    }

    updateEditCache(): void {
        this.editableTableData.forEach(item => {
            this.editCache[item.id] = {
                edit: false,
                data: { ...item }
            };
        });
    }

    startEdit(id: string, event: MouseEvent): void {
        event.preventDefault();
        event.stopPropagation();
        if (id !== 'total') {
            this.editCache[id].edit = true;
            this.editId = id;
        }
    }

    isEditableTd(id): boolean {
        if (this.pageType !== 'detail') {
            return id !== 'total' && this.editCache[id].edit;
        } else {
            return false;
        }
    }

    calcTableData(res): any {
        const waterFlowObj = res[0];
        const totalObj = _.find(res, o => {
            return o['id'] === 'total';
        });
        const keyArr = Object.keys(waterFlowObj);
        // const list = _.dropRight(res, 2);
        keyArr.forEach(key => {
            //  key以val开头 且值不为'-'
            if (key.slice(0, 3) === 'val' && totalObj[key] !== '-') {
                const daysLength = this.dispatchService.getMonthDays(this.month, this.dataType).length;
                totalObj[key] = this.dispatchService.getWaterByFlowYi(waterFlowObj[key], daysLength);
            }
        });
        _.fill(res, totalObj, 1, 2);
        // 更新概化图数据
        if (this.pensDate.pens.length > 0) {
            this.upDateGhtData();
        }
    }



    save(): void {
        const tableData = _.cloneDeep(this.editableTableData);
        const dataArr = [];
        const params = {
            reportId: '2',
            y: this.year,
            m: this.month,
            dataType: this.dataType,
            data: "",
        };
        if (this.month == 'D') {
            params.m = 'd';
        }
        tableData.forEach(row => {
            if (row.id != 'total') {
                const valData = { val: [] };
                this.valArr.forEach(item => {
                    valData.val.push(row[item]);
                });
                dataArr.push(valData);
            }
        });
        const flag = dataArr[0].val.includes("");
        if (flag) {
            this.message.warning('请填写完所有管理处调度计划再保存');
        } else {
            params.data = JSON.stringify(dataArr);
            this.fetchService.post<any>('plan/wrsReportData/add', params).subscribe(res => {
                this.message.success('保存成功');
            });
        }
    }

    isOptDisabled(): boolean {
        // 如果同年的所选月份大于当前月 或者 年份大于当前年 ，中下旬不可选
        return (moment(this.tenDaysMonth).month() > moment().month() && moment(this.tenDaysMonth).year() === moment().year()) || moment(this.tenDaysMonth).year() > moment().year();
        // return moment().date() > 20;
    }

    isXiaXunDisabled(): boolean {
        // 如果同年的所选月份 === 当前月 且 当前是上旬 ，下旬不可选
        return (moment(this.tenDaysMonth).month() === moment().month() && moment(this.tenDaysMonth).year() === moment().year() && moment().date() <= 10);
    }

    goBack(): void {
        this.router.navigate(['/dispatch-plan/hwh-dispatch'], {
            skipLocationChange: true,
        });
    }

    // 概划图 start
    getMapData() {
        this.fetchService.get<any>('base/wrsBrwaterReservior/query').subscribe(r => {
            this.ghtData = r;
            this.fetchService.get<any>('assets/data/dxzx/hwh-ght.json').subscribe(res => {
                this.pensDate = res;
                this.upDateGhtData();
            });
        });
    }
    upDateGhtData() {
        const ljxHQ = this.editableTableData[0].val1;
        const xhyHQ = this.editableTableData[0].val6;
        const szsHQ = this.editableTableData[0].val10;

        const ljxQ = this.ghtData.find(item => {
            return item.code === "40100780";
        }).flux;
        const xhyQ = this.ghtData.find(item => {
            return item.code === "40101750";
        }).flux;
        const szsQ = this.ghtData.find(item => {
            return item.code === "40102500";
        }).flux;

        const QS = this.ghtData.find(item => {
            return item.code === "NX-QS-Q";
        }).flux;

        // 数据处理
        for (const pen of this.pensDate.pens) {
            // 图标
            if (pen.data.id === '40100780') {
                const compareResult = ljxQ - ljxHQ;
                if (compareResult > 0) {
                    pen.image = '/wrs-web/assets/images/ght/newicons/shuiku01.png';
                } else if (compareResult === 0) {
                    pen.image = '/wrs-web/assets/images/ght/newicons/shuiku02.png';
                } else {
                    pen.image = '/wrs-web/assets/images/ght/newicons/shuiku03.png';
                }
            }
            if (pen.data.id === '40101750') {
                const compareResult = xhyQ - xhyHQ;
                if (compareResult > 0) {
                    pen.image = '/wrs-web/assets/images/ght/newicons/ZQ1.png';
                } else if (compareResult === 0) {
                    pen.image = '/wrs-web/assets/images/ght/newicons/ZQ2.png';
                } else {
                    pen.image = '/wrs-web/assets/images/ght/newicons/ZQ3.png';
                }
            }
            if (pen.data.id === '40102500') {
                const compareResult = szsQ - szsHQ;
                if (compareResult > 0) {
                    pen.image = '/wrs-web/assets/images/ght/newicons/ZQ1.png';
                } else if (compareResult === 0) {
                    pen.image = '/wrs-web/assets/images/ght/newicons/ZQ2.png';
                } else {
                    pen.image = '/wrs-web/assets/images/ght/newicons/ZQ3.png';
                }
            }

            // 流量
            if (pen.data.id === `40100780q`) {
                pen.text = ljxQ ? ljxQ + 'm³/s' : '-m³/s';
            }
            if (pen.data.id === `40101750q`) {
                pen.text = xhyQ ? xhyQ + 'm³/s' : '-m³/s';
            }
            if (pen.data.id === `40102500q`) {
                pen.text = szsQ ? szsQ + 'm³/s' : '-m³/s';
            }
            // 替换水量
            if (pen.data.id === `40100780s`) {
                const s = ljxQ ? this.dispatchService.getWaterByFlowYi(ljxQ) : '--';
                pen.text = s + '亿m³';
            }
            if (pen.data.id === `40101750s`) {
                const s = xhyQ ? this.dispatchService.getWaterByFlowYi(xhyQ) : '--';
                pen.text = s + '亿m³';
            }
            if (pen.data.id === `40102500s`) {
                const s = szsQ ? this.dispatchService.getWaterByFlowYi(szsQ) : '--';
                pen.text = s + '亿m³';
            }


            //  取水
            if (pen.data.id === 'NX-QS-Q') {
                pen.text = QS ? QS + 'm³/s' : '-m³/s';
            }
            if (pen.data.id === 'NX-QS-S') {
                const s = this.dispatchService.getWaterByFlowYi(QS);
                pen.text = s + '亿m³';
            }
            //  耗水
            if (pen.data.id === 'NX-HS-Q') {
                const q = xhyQ - szsQ;
                pen.text = q + 'm³/s';
            }
            if (pen.data.id === 'NX-HS-S') {
                const q = xhyQ - szsQ;
                pen.text = this.dispatchService.getWaterByFlowYi(q) + '亿m³';
            }
        }
        if (this.canvas) {
            // 重置画布数据
            this.canvas.open({
                id: '',
                version: '',
                name: 'new空白文件',
                desc: '',
                image: '',
                userId: '',
                class: '',
                component: false,
                shared: false
            });
        } else {
            // 创建画布
            this.canvas = new Le5leTopology.Topology('topology-canvas', this.canvasOptions);
        }
        this.canvas.open(this.pensDate);

        // 设置画布
        this.onResize();
    }
    // 窗口变化
    onResize() {
        const h = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().height;
        const w = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().width; // 设置画布
        this.rect = this.canvas.getRect();
        if (this.rect.width / this.rect.height > w / h) {
            this.canvas.scale(w / this.rect.width * 0.9);
        } else {
            this.canvas.scale(h / this.rect.height);
        }
        this.canvas.translate(w / 2 - this.rect.center.x, h / 2 - this.rect.center.y);
    }
    // 概划图 end
    // 获取 文件目录
    getFile(key?) {
        const param = {
            docId: 51,
            fileName: key,
            pageNum: 1,
            pageSize: 100
          };
        this.fetchService.post<any>('archives/wrsDocFile/list', param).subscribe(res => {
            if (Array.isArray(res.list)) {
                this.file = res.list[0];
            }
        });
    }
    // 文件预览
    viewFile(file, tplContent: TemplateRef<{}>): void {
        const that = this;
        this.fileType = file.fileName.split('.')[1];
        this.fileId = file.fileId;
        this.fileSrc = `${(window as any).environment.apiBaseUrl}comm/file/view/${file.fileId}`;

        this.tplModal = this.modal.create({
            nzTitle: '文件预览',
            nzContent: tplContent,
            nzWidth: 1100,
            nzFooter: null,
            nzMaskClosable: false,
            nzClosable: true,
            nzOnCancel(): void {
            that.destroyModal();
            }
        });
    }
    destroyModal() {
        this.tplModal.destroy();
    }
}
